<script setup>
import HeaderNavTabarSvg from '@/components/HeaderNavTabarSvg/HeaderNavTabar.vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import MyPicker from '@/components/MyPicker/MyPicker.vue'
import AuditApplicationSteps from '@/components/audit/function/auditApplicationSteps.vue'
import DescriptionAttachment from '@/components/audit/function/descriptionAttachment.vue'
import { ref } from 'vue'
import dayjs from 'dayjs'
import store from '@/store'
import { getWorkApi } from '@/api/customer.js'
import { addFinancialApplyControllerApi, selectOrderNoApi } from '@/api/attendance'
import { getUserProfile } from '@/api/system/user'
import approvalProcessState from '@/store/modules/approvalProcess'
import { isObjectValuesNotEmpty } from '@/utils/objIsnull.js'
// 弃用
const title = '货品抵账申请'

const entertainDateRef = ref(null)// 搜索的数据

const ItemRequisitionList = ref({
  date: '',
	// customerId: '',
	// customerName: '',
	businessModule:'',
	purchaseType:'',
	isContractScope:'',
	goodsPurpose: '',
  itemRequisitionDetail: [
    {
      goodsName: '',
      goodsNumber: '',
      goodsUnit: '',
			goodsUnitPrice:'',
			goodsMoney:'',
    },
  ],
	money:'',
	remark:''
})

const userId = ref(null)
const deptId = ref(null)
let attchment = ref([])
const getDesignDrawingsEmit = (emit) => {
  attchment.value = emit
}

const popupRef = ref(null)
const list1 = ref([{}])
const openPopupSelect = () => {
  popupRef.value.open()
}

// 单选弹窗选项点击事件
const itemClick = (item) => {
  if (item.item.label) {
    ItemRequisitionList.value.businessModule = item.item.label
    // ItemRequisitionList.value.assumptionCostsDep = item.item.dataArr.deptName
    ItemRequisitionList.value.deptId = item.item.name
    popupRef.value.close()
  }
}

function debounce(func, wait) {
  let timeout
  return function (...args) {
    const context = this
    clearTimeout(timeout)
    timeout = setTimeout(() => func.apply(context, args), wait)
  }
}

let inputChangeSearchDebounce = debounce(async function (emit) {
  let params = {
    pageNum: 1,
    pageSize: 50,
    orderId: emit,
  }
  let { code, rows } = await selectOrderNoApi(params)
  if (code === 200) {
    list1.value = rows.map((v) => {
      return {
        label: v.orderId,
        name: v.deptId,
        value: v.orderId,
        disabled: v.true,
        dataArr: v,
      }
    })
  }
}, 800)
const searchData = ref(null)
const inputChangeSearch = (emit) => {
  if (emit) {
    searchData.value = emit
    inputChangeSearchDebounce(emit)
  } else {
    list1.value = [{}]
  }
}

const clickSave = async () => {
	const RequiredItemList = JSON.parse(JSON.stringify(ItemRequisitionList.value))
	delete RequiredItemList.money
	delete RequiredItemList.remark
	console.log(RequiredItemList,'RequiredItemList')
	if(isObjectValuesNotEmpty(RequiredItemList)){
		console.log('111')
		let params = {
			orderId: ItemRequisitionList.value.businessModule,
			deptId: ItemRequisitionList.value.deptId,
			purchaseNature:ItemRequisitionList.value.purchaseType,
		  date:dayjs(ItemRequisitionList.value.date).format('YYYY-MM-DD hh:mm:ss'),
			isWithin:ItemRequisitionList.value.isContractScope,
			reason: ItemRequisitionList.value.goodsPurpose,
		  details:JSON.stringify(ItemRequisitionList.value.itemRequisitionDetail),
			money:ItemRequisitionList.value.money,
			remark:ItemRequisitionList.value.remark,
		  ruleId:'huopin',
		  type:'货品抵账申请',
		  attchment:JSON.stringify(attchment.value),
		  userId: userId.value,
			// deptId: deptId.value,
		  approve: approvalProcessState.state.approvalProcess
		}
		// console.log(params,'货品抵账申请提交params')
		let { code } = await addFinancialApplyControllerApi(params)
		if (code === 200) {
		  uni.showToast({
		    title: '提交成功',
		    duration: 1500,
		    icon: 'success',
		  })
		  setTimeout(() => {
		    uni.navigateBack()
		  }, 1000)
		}
	}else{
		uni.showToast({
		  title: '请输入完整数据',
		  icon: 'error',
		})
	}

}
const goHistoryView = ()=>{
  uni.navigateTo({
    url:'/components/TypeDefineModel?type=货品抵账申请&apiName=财务'
  })
}
const purchaseTypeRef = ref(null)
const purchaseTypeColumns = [['办公用品', '生产用料','其他']]
const purchaseTypeConfirm = (e) => {
  ItemRequisitionList.value.purchaseType = e.value[0]
}
const purchaseTypeFn = () => {
  purchaseTypeRef.value.open()
}

const formatter = (type, value) => {
  if (type === 'year') {
    return `${value}年`
  }
  if (type === 'month') {
    return `${value}月`
  }
  if (type === 'day') {
    return `${value}日`
  }
  if (type === 'hour') {
    return `${value}时`
  }
  if (type === 'minute') {
    return `${value}分`
  }
  return value
}

const customerPickerRef = ref(null) // 这个时候获取了子组件 Comp
// 客户信息
let customerList = ref([])
// 获取客户下拉菜单数据
const getWorkApiData = async (v = '') => {
  let params = {
    customerName: v,
  }
  let { code, data } = await getWorkApi(params)
  if (code == 200) {
    data.forEach((v) => {
      // customerList.value.push({
      //   label:  v.primaryClassification+'/'+ v.customerName,
      //   value: v.customerId,
      // })
			// 过滤掉 null
			customerList.value.push({
			  label:  [v.primaryClassification,v.customerName].filter(item => item != null).join('/'),
			  value: v.customerId,
			})
    })
    store.commit('setCustomerList', customerList.value)
  }
}

// 选择的客户数据
const getVlaue = (v) => {
  console.log(v)
  ItemRequisitionList.value.customerId = v.value
  ItemRequisitionList.value.customerName = v.label
  customerPickerRef.value.closePop()
}
// 打开模态床
const toggle = () => {
  customerPickerRef.value.toggle('bottom') // 调用子组件的 show 方法
}

const entertainDateFn = () => {
  entertainDateRef.value.open()
}
let entertainDatePicker = dayjs()
const entertainDateConfirm = (obj) => {
  ItemRequisitionList.value.date = dayjs(obj.value).format('YYYY-MM-DD')
}


const copyDetailItem = ()=>{
  ItemRequisitionList.value.itemRequisitionDetail.push(
    {
      goodsName: '',
      goodsNumber: '',
      goodsUnit: '',
      goodsUnitPrice: '',
      goodsMoney: '',
    }
  )
}
const deleteDetailItem = (index)=>{
  ItemRequisitionList.value.itemRequisitionDetail.splice(index,1)
}
const getUserProfileFn = async () => {
  let { code, data } = await getUserProfile()
  if (code === 200) {
    userId.value = data.userId
		deptId.value = data.deptId
  }
}

onLoad( ()=>{
  getUserProfileFn()
	getWorkApiData()
})
</script>

<template>
  <view>
    <HeaderNavTabarSvg :title="title">
      <image class="bukaSvg" src="/static/icon/auditSVG/buka.svg" @tap="goHistoryView"></image>
    </HeaderNavTabarSvg>

<!-- 		<MyPicker
		  @getVlaue="getVlaue"
		  ref="customerPickerRef"
		  popupTitle="请选择客户名称"
		>
		  <view class="picker-content" @tap="toggle">
		    <view class="measurement-info-list">
		      <text class="info-list-left isrequired">抵账客户名称</text>
		      <view class="info-list-right">
						<view class="uni-input" v-if="ItemRequisitionList.customerName"
						  >{{ ItemRequisitionList.customerName }}
						</view>
						<view class="uni-inputs" v-else>请选择</view>
		        <i class="iconfont icon-youjiantou"></i>
		      </view>
		    </view>
		  </view>
		</MyPicker> -->
		<view class="picker-content" @tap="openPopupSelect">
		  <view class="measurement-info-list">
		    <text class="info-list-left isrequired">抵账客户工单</text>
		    <view class="info-list-right">
		      <view class="uni-input" v-if="ItemRequisitionList.businessModule"
		        >{{ ItemRequisitionList.businessModule }}
		      </view>
		      <view class="uni-inputs" v-else>请选择</view>
		      <i class="iconfont icon-youjiantou"></i>
		    </view>
		  </view>
		</view>
		<hy-popup-select
		  v-model="ItemRequisitionList.businessModule"
		  :list="list1"
		  :filterKeys="['label', 'name']"
		  ref="popupRef"
		  @itemClick="itemClick"
		  @inputChange="inputChangeSearch"
		>
		  <template v-slot="{ item, index }">
		    <view class="card-list" style="margin-top: 12rpx" v-if="item?.dataArr?.customerName">
		
		      <view class="header-content">
		        <text> {{ item.dataArr.customerName || '未知' }}</text>
		        <text> {{ item.orderId || '未知' }}</text>
		      </view>
		      <view class="main-content">
		        <h4>{{ item.dataArr.customerStore || '未知' }}</h4>
		        <p>{{ item.dataArr.invoiceStatus || '未知' }}</p>
		      </view>
		      <view class="main-floor">
		        <view class="floot-svg">
		          <image src="@/static/svg/money.svg"></image>
		          <text> {{ item.dataArr.totalOrderAmount || '未知' }}</text>
		          <text>元</text>
		        </view>
		        <p class="floor-date">
		          {{ dayjs(item.dataArr.orderDate).format('YYYY-MM-DD') || '未知' }}
		        </p>
		      </view>
		    </view>
		  </template>
		</hy-popup-select>
		
		
		<view class="picker-content">
		  <view class="measurement-info-list">
		    <text class="info-list-left isrequired">是否在合同约定抵货额度范围内</text>
		    <view class="info-list-right">
		      <view class="uni-input"
		        >
							<uv-radio-group v-model="ItemRequisitionList.isContractScope" placement="row">
								<uv-radio name="是" label="是"></uv-radio>
								<uv-radio name="否" activeColor="red" label="否"></uv-radio>
							</uv-radio-group>
		      </view>
		    </view>
		  </view>
		</view>
		
		<view class="picker-content" @tap="entertainDateFn">
		  <view class="measurement-info-list">
		    <text class="info-list-left isrequired">抵货日期</text>
		    <view class="info-list-right">
		      <view class="uni-input" v-if="ItemRequisitionList.date"
		        >{{ ItemRequisitionList.date }}
		      </view>
		      <view class="uni-inputs" v-else>请选择</view>
		      <i class="iconfont icon-youjiantou"></i>
		    </view>
		  </view>
		</view>
		<uv-datetime-picker
		  ref="entertainDateRef"
		  v-model="entertainDatePicker"
		  :formatter="formatter"
		  mode="date"
		  @confirm="entertainDateConfirm"
		/>
		
		<view class="textarea-box">
		  <text class="info-list-left isrequired">货品用途</text>
		  <textarea
		    v-model="ItemRequisitionList.goodsPurpose"
		    class="textinfo-list"
		    placeholder="请输入"
		  ></textarea>
		</view>
		
		<view class="picker-content" @tap="purchaseTypeFn">
		  <view class="measurement-info-list">
		    <text class="info-list-left isrequired">采购类型</text>
		    <view class="info-list-right">
		      <view class="uni-input" v-if="ItemRequisitionList.purchaseType"
		        >{{ ItemRequisitionList.purchaseType }}
		      </view>
		      <view class="uni-inputs" v-else>请选择</view>
		      <i class="iconfont icon-youjiantou"></i>
		    </view>
		  </view>
		</view>
		<uv-picker
		  ref="purchaseTypeRef"
		  :columns="purchaseTypeColumns"
		  @confirm="purchaseTypeConfirm"
		></uv-picker>

    <view
      class="detail-itemRequisition"
      v-for="(item, index) in ItemRequisitionList.itemRequisitionDetail"
      :key="index"
    >
      <view class="detail-item">
        <p style="color: #86909C">采购明细{{index+1}}</p>
        <p class="detail-utils">
          <text @tap="copyDetailItem">复制</text>
          <text @tap="deleteDetailItem(index)" v-if="ItemRequisitionList.itemRequisitionDetail.length > 1">删除</text>
        </p>
      </view>

      <view class="picker-content">
        <view class="measurement-info-list">
          <text class="info-list-left isrequired">货品名称</text>
          <view class="info-list-right">
            <view class="info-content">
              <input
                adjust-position
                type="text"
                class="uni-input"
                placeholder="请输入"
                v-model="item.goodsName"
              />
            </view>
          </view>
        </view>
      </view>
      <view class="picker-content">
        <view class="measurement-info-list">
          <text class="info-list-left isrequired">数量</text>
          <view class="info-list-right">
            <view class="info-content">
              <input
                adjust-position
                type="text"
                class="uni-input"
                placeholder="请输入"
                v-model="item.goodsNumber"
              />
            </view>
          </view>
        </view>
      </view>
      <view class="picker-content">
        <view class="measurement-info-list">
          <text class="info-list-left isrequired">单位</text>
          <view class="info-list-right">
            <view class="info-content">
              <input
                adjust-position
                type="text"
                class="uni-input"
                placeholder="请输入"
                v-model="item.goodsUnit"
              />
            </view>
          </view>
        </view>
      </view>
			
			<view class="picker-content">
			  <view class="measurement-info-list">
			    <text class="info-list-left isrequired">单价</text>
			    <view class="info-list-right">
			      <view class="info-content" style="display: flex; align-items: center">
			        <input
			          adjust-position
			          type="text"
			          class="uni-input"
			          placeholder="请输入"
			          v-model="item.goodsUnitPrice"
			        />
			        <p style="font-size: 28rpx; line-height: 1.4em">元</p>
			      </view>
			    </view>
			  </view>
			</view>
			
			<view class="picker-content">
			  <view class="measurement-info-list">
			    <text class="info-list-left isrequired">金额</text>
			    <view class="info-list-right">
			      <view class="info-content" style="display: flex; align-items: center">
			        <input
			          adjust-position
			          type="text"
			          class="uni-input"
			          placeholder="请输入"
			          v-model="item.goodsMoney"
			        />
			        <p style="font-size: 28rpx; line-height: 1.4em">元</p>
			      </view>
			    </view>
			  </view>
			</view>


    </view>
		
    <view class="picker-content">
      <view class="measurement-info-list">
        <text class="info-list-left">总金额</text>
        <view class="info-list-right">
          <view class="info-content" style="display: flex; align-items: center">
            <input
              adjust-position
              type="text"
              class="uni-input"
              placeholder="请输入"
              v-model="ItemRequisitionList.money"
            />
            <p style="font-size: 28rpx; line-height: 1.4em">元</p>
          </view>
        </view>
      </view>
    </view>
		
		<view class="textarea-box">
		  <text class="info-list-left">备注</text>
		  <textarea
		    v-model="ItemRequisitionList.remark"
		    class="textinfo-list"
		    placeholder="请输入"
		  ></textarea>
		</view>

    <!--    说明附件-->
    <DescriptionAttachment @getDesignDrawingsEmit="getDesignDrawingsEmit"/>
    <!--    审批流程-->
    <AuditApplicationSteps :ruleId="'huopin'"/>
    <!--    底部占位符-->
    <view class="blank"></view>
    <!--    保存-->
    <view class="buttonContainer">
      <button class="buttonClass" @click="clickSave">提交</button>
    </view>
  </view>
</template>

<style lang="scss" scoped>
@import '@/static/style/index.scss';

.bukaSvg {
  width: 32rpx;
  height: 32rpx;
}

.buttonContainer {
  position: fixed;
  bottom: 0;
  display: flex;
  justify-content: center;
  width: 100%;
  align-items: center;
  padding: 16rpx;
  background-color: #fff;
}

.buttonClass {
  display: flex;
  width: 686rpx;
  height: 72rpx;
  justify-content: center;
  align-items: center;
  background: #165dff;
  border-radius: 16rpx;
  color: #fff;
  font-size: 32rpx;
  //margin-top: 40rpx;
  overflow: hidden;
}

.uni-inputs {
  color: #86909c !important;
}

.uni-input {
  text-align: right;
  font-size: 28rpx;
	.uv-radio-label--left{
		margin-right: 10rpx;
	}
}

.blank {
  height: calc(72rpx + 32rpx + 20rpx);
}

.textarea-box {
  background: #fff;
  padding: 20rpx;
  margin-top: 20rpx;

  .info-list-left {
    // @include font-color-auxiliary;
    color: #1d2129;
    font-size: $font-size-base;
  }

  .textinfo-list {
    margin-top: 20rpx;
    width: 100%;
    height: 200rpx;
  }
}

.bukabanci {
  .info-content {
    color: #86909c !important;
  }

  .info-list-left {
    // @include font-color-auxiliary;
    color: #86909c !important;
  }
}

.textarea-box {
  background: #fff;
  padding: 20rpx;
  margin-top: 20rpx;

  .info-list-left {
    // @include font-color-auxiliary;
    color: #1d2129;
    font-size: $font-size-base;
  }

  .textinfo-list {
    margin-top: 20rpx;
    width: 100%;
    height: 200rpx;
  }
}

.popup-content {
  background: #f7f8fa;

  .header-box {
    padding: 30rpx 20rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;

    p {
      color: #1d2129;
      font-size: 34rpx;
      font-weight: 500;
    }

    .module-image-ba {
      border-radius: 32rpx;
      background: #f2f3f5;
      width: 45rpx;
      height: 45rpx;
      display: flex;
      align-items: center;
      justify-content: center;

      image {
        width: 32rpx;
        height: 32rpx;
      }
    }
  }

.card-list {
  padding: 24rpx 32rpx;
  width: 686rpx;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
  flex-direction: column;
  background-color: #ffffff;
  border-radius: 16rpx;
  border: 1rpx solid #e5e6eb;
  margin-bottom: 16rpx;

  .header-content,
  .main-content,
  .main-floor {
    @include flex($justify: space-between);
    color: #86909c;
    font-size: 24rpx;
    font-weight: 400;
  }

  .main-content {
    margin: 10rpx 0;

    h4 {
      color: #1d2129;
      font-size: 32rpx;
    }

    p {
      @include flex($justify: center, $align: center);
      padding: 0 8rpx;
      border-radius: 10rpx;
      min-width: 97rpx;
    }

    .待设计,
    .未下单,
    .待核算,
    .待上传安装图片,
    .待上传拆除照片 {
      color: #165dff;
      background-color: #e8f3ff;
    }

    .已核算,
    .已下单,
    .审核通过,
    .已通过 {
      color: #00b42a;
      background-color: #e8ffea;
    }

    .待审核 {
      color: #ff7d00;
      background-color: #fff7e8;
    }

    .驳回 {
      color: $btn-error-color;
      background-color: $btn-error-bg;
    }
  }

  .main-floor {
    .floot-svg {
      @include flex($align: center);

      image {
        width: 28rpx;
        height: 28rpx;
      }

      text {
        color: #1d2129;
      }
    }
  }

  .btn-install-order-list {
    margin-top: 20rpx;

    button {
      height: 56rpx;
      @include flex($justify: center, $align: center);
      border: none;
    }

    .btn-flex {
      @include flex($justify: space-between, $align: center);

      .接单 {
        background-color: #165dff;
        color: #fff;
      }

      button {
        width: 291rpx;
      }
    }

    .进行中 {
      background-color: #e8f3ff;
      color: #165dff;
    }

    .已拒接,
    .拒接 {
      background-color: #ffece8;
      color: #f53f3f;
    }

    .已完工 {
      background-color: #e8ffea;
      color: #00b42a;
    }

    .已超时 {
      background-color: #fff7e8;
      color: #ff7d00;
    }

    .row-btn {
      width: 100%;
    }
  }
}
}

.detail-itemRequisition{
  .detail-item{
  padding: 10rpx 30rpx;
    @include flex($align: center, $justify: space-between);

    .detail-utils{
      @include flex($align: center, $justify: space-between);
      width: 150rpx;
      color: #165DFF;
    }


  }
  .text-info{
    color: #86909C;
    padding: 20rpx 30rpx;
    display: inline-block;
  }
}


.measurement-info-list {
  @include flex($align: center, $justify: space-between);
  padding: $spacing-row-base;
  background: #fff;
  margin-top: 16rpx;

  .info-list-left {
    // @include font-color-auxiliary;
    color: #1d2129;
    font-size: $font-size-base;
  }

  .info-list-right {
    @include flex($align: center);

    .info-content {
      @include textStyleBase;
      font-size: 34rpx;
    }

    .iconfont {
      margin-left: 16rpx;
      // @include font-color-auxiliary;
      color: $uni-fc-fu-lin;
    }
  }

  .unit {
    // @include font-color-auxiliary;
    color: $uni-fc-fu-lin;
  }
}
</style>
